package sistemaweb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import sistemaweb.excepcion.LoginExcepcion;
import sistemaweb.excepcion.DAOExcepcion;
import sistemaweb.modelo.Persona;
import sistemaweb.conex.ConexDB;



public class PersonaDAO extends BaseDAO{

	public Persona validar(String correo, String password)throws DAOExcepcion, LoginExcepcion {
		
		String query = "select Nombres, ApePaterno, ApeMaterno, Correo, idUsuario from persona where Correo=? and Password=?";
		
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Persona vo = new Persona();
		
		try{
			con = ConexDB.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, correo);
			stmt.setString(2, password);
			rs = stmt.executeQuery();
			
			if (rs.next()) {
				vo.setNombres(rs.getString("nombres"));
				vo.setApepaterno(rs.getString("apepaterno"));
				vo.setApematerno(rs.getString("apematerno"));
				vo.setCorreo(rs.getString("correo"));
				vo.setIdUsuario(rs.getString("idUsuario"));
				
			}else{
				throw new LoginExcepcion("No existe");
				}
			} catch (LoginExcepcion e){
				System.err.println(e.getMessage());
				throw new LoginExcepcion(e.getMessage());
			} catch (SQLException e){
				System.err.println(e.getMessage());
				throw new DAOExcepcion(e.getMessage());				
		}finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		
		return vo;
		
	}
	
	
	public Persona insertar(Persona vo) throws DAOExcepcion{
		
		String query = "insert into persona (Nombres, ApePaterno, ApeMaterno, Sexo, Correo, Password, idTipoDocumento," 
				+ "NroDocumento, Celular, Direccion, FechaCreacion) "
				+ "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
		
		System.err.println(query);
		Connection con = null;
		PreparedStatement stmt = null;
		
		try {
			con = ConexDB.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, vo.getNombres());
			stmt.setString(2, vo.getApepaterno());
			stmt.setString(3, vo.getApematerno());
			stmt.setString(4, vo.getSexo());
			stmt.setString(5, vo.getCorreo());
			stmt.setString(6, vo.getPassword());
			stmt.setInt(7, vo.getTipodoc());
			stmt.setString(8, vo.getNumdoc());
			stmt.setString(9, vo.getCelular());
			stmt.setString(10, vo.getDireccion());
			
			int i = stmt.executeUpdate();
			if (i != 1){
				throw new SQLException("No se pudo insertar");
			}
		}catch (SQLException e){
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}finally{
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		
		return vo;
	}
	
	
}
